package com.shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.shop.entity.User;
import com.shop.service.UserService;
import com.shop.service.util.JwtUtil;
import com.shop.util.CookieUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Producer producer;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private final int EMAIL_CODE_OVER_TIME_OUT = 5;

    /**
     * 用户注册
     *
     * @param user      用户信息
     * @param emailCode 邮箱验证码
     * @return 注册状态码
     */
    @RequestMapping("/registerUser")
    public String registerUser(User user, Integer emailCode) {
        synchronized (user.getUsername().intern()) {
            int saveResult = -1;
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("username", user.getUsername());
            User one = userService.getOne(query);
            if (one != null) {
                return "用户已存在";
            }
            String matchEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
            if (!user.getEmail().matches(matchEmail) || "".equals(user.getEmail())) {
                return "请输入正确格式的邮箱";
            }
            Integer autoCode = (Integer) redisTemplate.opsForValue().get(user.getEmail());
            if (autoCode != null && autoCode.equals(emailCode)) {
                saveResult = userService.saveNewUser(user);
            }

            if (saveResult != 1) {
                return "验证码错误";
            }
        }
        Map<String, String> emailMap = new HashMap<>();
        emailMap.put("email", user.getEmail());
        emailMap.put("subject", "欢迎使用蜗牛购物");
        emailMap.put("text", "欢迎!");
        rabbitTemplate.convertAndSend("","email_queue",emailMap);
        return "200";
    }

    /**
     * 发送邮箱验证码
     *
     * @param email 邮箱地址
     * @return 状态码
     */
    @RequestMapping("/getEmailCode")
    public String getEmailCode(String email) {

        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        String matchEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        if (!email.matches(matchEmail) || "".equals(email)) {
            return "请输入正确格式的邮箱";
        }
        String authCode = (String) opsForValue.get(email);
        if (authCode != null) {
            return "验证码未过期";
        }
        int num = new Random().nextInt(9000) + 1000;
        String code = String.valueOf(num);
        Map<String, String> emailMap = new HashMap<>();
        emailMap.put("email", email);
        emailMap.put("subject", "欢迎使用蜗牛购物");
        emailMap.put("text", "您的验证码为 " + code + " ,有效期为5分钟,请尽快使用");
        rabbitTemplate.convertAndSend("","email_queue",emailMap);

        opsForValue.set(email, code, EMAIL_CODE_OVER_TIME_OUT, TimeUnit.MINUTES);
        return "验证码已发送，请注意查收!验证码5分钟内有效！";
    }

    /**
     * 生成基于文本的图片以供用户验证，并将生成的文本设置为会话属性。
     *
     * @param response - 用于发送图像的 HTTP 响应对象。
     * @param request  - HTTP 请求对象。
     * @throws Exception 如果生成图像时发生错误，将抛出异常。
     */
    @RequestMapping("/getImgCode")
    public void getImgCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        request.getSession().setAttribute("imgCode", text);
        response.setContentType("image/jepg");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    /**
     * 用户登录方法，验证用户名、密码和验证码，生成一个 JWT 并将其存储在 Redis 中，然后将 JWT 作为 Cookie 添加到响应中。
     *
     * @param username - 用户名。
     * @param password - 密码。
     * @param code     - 验证码。
     * @param request  - HTTP 请求对象。
     * @param response - HTTP 响应对象。
     * @return 如果用户名或密码错误，将返回 "用户名和密码错误"，如果验证码错误，将返验证码错误回 ""，否则返回 "200"。
     */
    @RequestMapping("/login")
    public String login(String username, String password, String code, HttpServletRequest request, HttpServletResponse response) {
        String imgCode = (String) request.getSession().getAttribute("imgCode");
        if (!imgCode.equalsIgnoreCase(code)) {
            return "验证码错误";
        }
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "用户名和密码错误";
        }
        User loginUser = userService.login(username, password);
        if (loginUser == null) {
            return "用户名和密码错误";
        }
        Map<String, Object> tokenInfo = new HashMap<>();
        tokenInfo.put("username", username);
        String token = JwtUtil.createToken(20, tokenInfo);
        redisTemplate.opsForValue().set(token, username, 40, TimeUnit.MINUTES);
        CookieUtils.addCookie(response, "tokenCookie", token, false);
        request.getSession().removeAttribute("imgCode");
        return "200";
    }

    /**
     * 用于检查用户是否已经登录，如果是，则返回用户名。
     *
     * @param request - HTTP 请求对象。
     * @return 如果已登录，则返回用户名，否则返回空字符串。
     */
    @RequestMapping("/isLogin")
    public String isLogin(HttpServletRequest request) {
        String loginUser = "";
        String tokenCookie = CookieUtils.getCookieValueByName(request, "tokenCookie");
        if (tokenCookie != null) {
            loginUser = JwtUtil.parseValueWithoutException(tokenCookie, "username");
        }

        return StringUtils.isEmpty(loginUser) ? "" : loginUser;
    }

    /**
     * 用户登出方法，删除 Redis 中的 JWT 并将 Cookie 标记为已过期。
     *
     * @param request  - HTTP 请求对象。
     * @param response - HTTP 响应对象。
     * @return 返回 "200"。
     */
    @RequestMapping("/logout")
    public String getLogout(HttpServletRequest request, HttpServletResponse response) {

        String token = CookieUtils.getCookieValueByName(request, "tokenCookie");
        if (token != null) {
            redisTemplate.delete(token);
            CookieUtils.addCookie(response, "tokenCookie", token, true);
        }
        return "200";
    }


}

